package com.javaee.wordtree.service;

import com.javaee.wordtree.entity.*;
import com.javaee.wordtree.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class StoryAutoGenerationService {
    
    @Resource
    private StoryTemplateMapper storyTemplateMapper;
    
    @Resource
    private StoryPageMapper storyPageMapper;
    
    @Resource
    private UserStoryProgressMapper userStoryProgressMapper;
    
    @Resource
    private MemoryService memoryService;
    
    @Resource
    private DeepseekService deepseekService;


    
    
    /**
     * 用户登录时异步为用户生成个性化故事
     */
    @Async
    public CompletableFuture<Void> generateStoriesForUser(String userId) {
        log.info("开始为用户 {} 生成个性化故事", userId);
        
        try {
            // 1. 获取用户的学习单词
            List<Word> learnedWords = memoryService.getTodayLearnedWords(userId);
            List<String> wordList = learnedWords.stream()
                .map(Word::getWord)
                .limit(8) // 限制单词数量
                .collect(ArrayList::new, (list, word) -> list.add(word), ArrayList::addAll);
            
            if (wordList.isEmpty()) {
                // 如果用户还没有学习单词，使用默认单词
                wordList = Arrays.asList("adventure", "journey", "discover", "mystery", "explore", "friend", "brave", "magic");
            }
            
            // 2. 生成3个不同主题的故事
            String[] themes = {"adventure", "mystery", "fantasy"};
            for (String theme : themes) {
                generateStoryForTheme(userId, wordList, theme);
                
                // 避免API调用过于频繁
                Thread.sleep(3000);
            }
            
            log.info("用户 {} 的故事生成完成", userId);
            
        } catch (Exception e) {
            log.error("为用户 {} 生成故事失败", userId, e);
        }
        
        return CompletableFuture.completedFuture(null);
    }
    
    @Transactional
    private void generateStoryForTheme(String userId, List<String> wordList, String theme) {
        try {
            // 1. 检查是否已有该主题的故事
            if (hasRecentStoryForTheme(userId, theme)) {
                log.info("用户 {} 已有最近的 {} 主题故事，跳过生成", userId, theme);
                return;
            }
            
            // 2. 生成故事模板
            StoryTemplate template = new StoryTemplate();
            template.setTitle(generateStoryTitle(theme, wordList));
            template.setDescription("基于用户学习单词的个性化故事");
            template.setDifficultyLevel("beginner");
            template.setWordList(new ArrayList<>(wordList));
            template.setTheme(theme);
            storyTemplateMapper.insert(template);
            
            // 3. 生成故事开始页面
            StoryPage rootPage = generateStoryIntroduction(template.getId(), wordList, theme);
            if (rootPage != null) {
                storyPageMapper.insert(rootPage);
                
                // 4. 生成故事分支
                generateStoryBranches(template.getId(), rootPage, wordList, 1, 3);
                
                // 5. 更新模板总页数
                int totalPages = storyPageMapper.findByTemplateId(template.getId()).size();
                template.setTotalPages(totalPages);
                storyTemplateMapper.updateById(template);
                
                log.info("为用户 {} 生成 {} 主题故事成功，共 {} 页", userId, theme, totalPages);
            }
            
        } catch (Exception e) {
            log.error("生成 {} 主题故事失败", theme, e);
        }
    }
    
    private boolean hasRecentStoryForTheme(String userId, String theme) {
        // 检查是否在最近24小时内已生成过该主题的故事
        List<StoryTemplate> recentTemplates = storyTemplateMapper.findLatestTemplates(10);
        return recentTemplates.stream()
            .anyMatch(template -> theme.equals(template.getTheme()) && 
                     template.getCreatedAt().isAfter(java.time.LocalDateTime.now().minusHours(24)));
    }
    
    private StoryPage generateStoryIntroduction(Long templateId, List<String> words, String theme) {
        String prompt = buildIntroPrompt(words, theme);
        
        try {
            DeepseekResponse response = deepseekService.callDeepseekApi(prompt).block();
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                return parseStoryContent(templateId, null, null, content, 1);
            }
        } catch (Exception e) {
            log.error("生成故事介绍失败", e);
        }
        
        return null;
    }
    
    private void generateStoryBranches(Long templateId, StoryPage parentPage, List<String> words, int currentDepth, int maxDepth) {
        if (currentDepth >= maxDepth || parentPage.getChoices() == null || parentPage.getChoices().isEmpty()) {
            return;
        }
        
        for (int i = 0; i < Math.min(parentPage.getChoices().size(), 2); i++) { // 限制为2个分支
            String choice = parentPage.getChoices().get(i);
            
            StoryPage nextPage = generateStoryBranch(templateId, parentPage, i, choice, words, currentDepth, maxDepth);
            if (nextPage != null) {
                storyPageMapper.insert(nextPage);
                
                if (!nextPage.getIsEnding()) {
                    generateStoryBranches(templateId, nextPage, words, currentDepth + 1, maxDepth);
                }
            }
        }
    }
    
    private StoryPage generateStoryBranch(Long templateId, StoryPage parentPage, int choiceIndex, 
                                        String choice, List<String> words, int currentDepth, int maxDepth) {
        
        boolean isLastLevel = (currentDepth >= maxDepth - 1);
        String prompt = buildBranchPrompt(parentPage, choice, words, isLastLevel);
        
        try {
            DeepseekResponse response = deepseekService.callDeepseekApi(prompt).block();
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                
                StoryPage page = parseStoryContent(templateId, parentPage.getId(), choiceIndex, content, currentDepth + 1);
                if (isLastLevel) {
                    page.setIsEnding(true);
                    page.setChoices(new ArrayList<>());
                }
                return page;
            }
        } catch (Exception e) {
            log.error("生成故事分支失败", e);
        }
        
        return null;
    }
    
    private StoryPage parseStoryContent(Long templateId, Long parentPageId, Integer choiceIndex, String content, int pageNumber) {
        StoryPage page = new StoryPage();
        page.setTemplateId(templateId);
        page.setParentPageId(parentPageId);
        page.setChoiceIndex(choiceIndex);
        page.setPageNumber(pageNumber);
        
        // 解析英文和中文内容
        String[] sections = content.split("(?i)Chinese:|中文:");
        if (sections.length >= 2) {
            page.setEnglishContent(extractEnglishContent(sections[0]));
            page.setChineseContent(extractChineseContent(sections[1]));
        } else {
            page.setEnglishContent(content);
            page.setChineseContent("");
        }
        
        // 解析选择项
        List<String> choices = extractChoices(content);
        page.setChoices(choices);
        page.setIsEnding(choices.isEmpty());
        
        return page;
    }
    
    private String extractEnglishContent(String section) {
        return section.replaceAll("(?i)English:", "").trim();
    }
    
    private String extractChineseContent(String section) {
        String[] parts = section.split("(?i)Choices:|选择:");
        return parts[0].trim();
    }
    
    private List<String> extractChoices(String content) {
        List<String> choices = new ArrayList<>();
        String[] lines = content.split("\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.matches("^\\d+\\.\\s*.+")) {
                String choice = line.replaceFirst("^\\d+\\.\\s*", "");
                choices.add(choice);
            }
        }
        
        return choices;
    }
    
    private String generateStoryTitle(String theme, List<String> words) {
        String wordPreview = String.join(", ", words.subList(0, Math.min(3, words.size())));
        return String.format("The %s Adventure - %s", 
            theme.substring(0, 1).toUpperCase() + theme.substring(1), wordPreview);
    }
    
    private String buildIntroPrompt(List<String> words, String theme) {
        return "Create an engaging " + theme + " story introduction for English learners. " +
               "Use these words naturally: " + String.join(", ", words) + ". " +
               "Format: English:\n<story>\n\nChinese:\n<translation>\n\nChoices:\n1. <choice1>\n2. <choice2>";
    }
    
    private String buildBranchPrompt(StoryPage parentPage, String choice, List<String> words, boolean isEnding) {
        String prompt = "Continue the story based on: " + parentPage.getEnglishContent() + 
                       "\nUser chose: " + choice + 
                       "\nUse words: " + String.join(", ", words) + "\n\n";
                       
        if (isEnding) {
            prompt += "Write a satisfying ending. Format: English:\n<ending>\n\nChinese:\n<translation>";
        } else {
            prompt += "Continue the story and provide 2 choices. Format: English:\n<story>\n\nChinese:\n<translation>\n\nChoices:\n1. <choice1>\n2. <choice2>";
        }
        
        return prompt;
    }
}